package com.zlzlib.okhttp.xml;


import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 构造xml格式的数据
 *
 * @DateTime: 2021/2/19 17:31
 * @Author zlz
 * @Version 1.0
 */
public class BaseXmlContent {
    /**
     * 标签 名称  <name>  </name>
     */
    private final String name;
    /**
     * 标签 内容
     */
    private final List<BaseXmlContent> values;
    /**
     * 普通内容
     */
    private String valueString = "";
    /**
     * 属性
     */
    private final Map<String, String> attribute;

    public BaseXmlContent(String name) {
        this.name = name;
        attribute = new HashMap<>();
        values = new ArrayList<>();
    }

    public String getValueString() {
        return valueString;
    }

    public void setValueString(String valueString) {
        this.valueString = valueString;
    }

    public BaseXmlContent addAttribute(String key, String value) {
        attribute.put(key, value);
        return this;
    }

    public BaseXmlContent addValue(BaseXmlContent xmlContent) {
        values.add(xmlContent);
        return this;
    }

    public List<BaseXmlContent> getValues() {
        return values;
    }

    public Map<String, String> getAttribute() {
        return attribute;
    }

    @Override
    public String toString() {
        StringBuilder content = new StringBuilder();
        content.append("<").append(name);
        //添加属性
        if (!attribute.isEmpty()) {
            for (Map.Entry<String, String> val : attribute.entrySet()) {
                content.append(" ").append(val.getKey()).append("=\"").append(val.getValue()).append("\"");
            }
        }
        if (StringUtils.hasLength(valueString)) {
            content.append(">").append(valueString).append("</").append(name).append(">");
        } else if (!values.isEmpty()) {
            content.append(">");
            for (BaseXmlContent baseXmlContent : values) {
                content.append(baseXmlContent.toString());
            }
            content.append("</").append(name).append(">");
        } else {
            content.append("/>");
        }
        return content.toString();
    }
}
